package com.lsa.letcode.the71.simplifyPath;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;

public class Solution {
	enum Clazz{
		CUR_DIR,
		PARENT_DIR,
		ORDINARY,
		EMPTY
	}
	
	private static final Map<String, Clazz> dir2Clazz = new HashMap<>();
	static{
		dir2Clazz.put(".", Clazz.CUR_DIR);
		dir2Clazz.put("..", Clazz.PARENT_DIR);
	}
	
	private static Clazz dir2Clazz(String dir) {
		if (dir.isEmpty()) {
			return Clazz.EMPTY;
		}
		else {
			Clazz clazz = dir2Clazz.get(dir);
			if (clazz != null){
				return clazz;
			}
			else {
				return Clazz.ORDINARY;
			}
		}
	}
	
    public String simplifyPath(String path) {
    	Stack<String> stack = new Stack<>();
    	StringTokenizer st = new StringTokenizer(path, "/");
    	
    	
		while(st.hasMoreTokens()) {
			String dir = st.nextToken();
			Clazz clazz = dir2Clazz(dir);
			if (Clazz.CUR_DIR == clazz || Clazz.EMPTY == clazz) {
				continue;
			}
			else if (Clazz.PARENT_DIR == clazz) {
				if (!stack.isEmpty()) {
					stack.pop();
				}
			}
			else { // Clazz.ORDINARY
				stack.push(dir);
			}
		}
		
		StringBuilder sb = new StringBuilder("/");
		boolean isFirst = true;
		for (String dir : stack) {
			if (!isFirst) {
				sb.append("/");
			}
			isFirst = false;
			sb.append(dir);
		}
        return sb.toString();
    }
}
